var msMessage = new i18nMessage('../../servlet/I18nMessageServlet?keyPrefix=ui.measurespecification');
var ctStature = new i18nMessage('../../servlet/CodeTableServlet?name=CtStature');
var ctCollar = new i18nMessage('../../servlet/CodeTableServlet?name=CtCollarType');
var ctProductFamily = new i18nMessage('../../servlet/CodeTableServlet?name=CtProductFamily');
var msStore;
var msGrid;
var msWindow;

var selectMs = function(selectCallback, ctStatureCode, ctCollarTypeCode){
	var msUrl = '../../servlet/BiMeasureSpecificationServlet?action=4';
	if(ctCollarTypeCode){
		msUrl += '&ctCollarType=' + ctCollarTypeCode;
	}
	if(ctStatureCode){
		msUrl += '&ctStature=' + ctStatureCode;
	}
    if (!msWindow) {
        msWindow = new Ext.Window({
            title: message.get('message.combo.pleaseselect'),
            layout: 'fit',
            width: 800,
            height: 605,
            closeAction: 'hide',
            plain: true,
            modal: true,
            items: [{
                id: 'msPanel',
                region: 'center',
                bodyStyle: {
                    background: '#ffffff',
                    padding: '7px'
                },
                html: '<div id="msDiv"></div>'
            }]
        });
    }
    msWindow.show();
    
    if (msGrid) {
		msStore.proxy = new Ext.data.HttpProxy({
				url : msUrl
			});
		msStore.reload();
        return;
    }
    
    msStore = new Ext.data.Store({
         url: msUrl,
                    
        // the return will be XML, so lets set up a reader
        reader: new Ext.data.XmlReader({
            // records will have an "Item" tag
            record: 'item',
            id: 'id',
            totalRecords: 'itemTotal'
        }, [ // set up the fields mapping into the xml doc
        // The first needs mapping, the others are very basic
        'index', 'name', 'ctStature', 'ctStatureCode', 'ctCollarType','isAddItem','customerReference',
         'biFranceCustomer', 'id', 'patronage', 'realPhoto1Name', 'realPhoto2Name', 'ctProductFamily', {
		 	name: 'biFranceCustomer.name',
		 	mapping: 'customerName'
		 }, {
		 	name: 'biFranceCustomer.department',
		 	mapping: 'customerDepartment'
		 }]),
        
        remoteSort: true
    });
    
    msStore.setDefaultSort('id', 'desc');
    
    var filters = new Ext.grid.GridFilters({
        filters:[
		    {type: 'string',  dataIndex: 'name'},
			{type: 'string',  dataIndex: 'patronage'},
			{type: 'string',  dataIndex: 'customerReference'},
			{
			      type: 'list',  
			      dataIndex: 'ctStature', 
			      options: ctStature.getCtArray()
		    },
			{
			      type: 'list',  
			      dataIndex: 'ctCollarType', 
			      options: ctCollar.getCtArray()
		    },
			{type: 'string', dataIndex: 'biFranceCustomer.name'},
			{type: 'string', dataIndex: 'biFranceCustomer.department'}
		]
    });
    
    function renderSelectItem(value, p, record){
        return String.format('<a href="javascript: selectMsCallback(\'{0}\', \'{1}\', \'{2}\', \'{3}\');msWindow.hide();"><img src="../../images/icons/arrow_rotate_clockwise.png" title="' + message.get('message.list.select') + '" /></a>', record.data.id, record.data.patronage, record.data.realPhoto1Name, record.data.realPhoto2Name);
    }
    // create the grid
    msGrid = new Ext.grid.GridPanel({
        title: msMessage.get('ui.measurespecification.listtitle'),
        store: msStore,
        stripeRows: true,
        plugins: filters,
        height: 560,
        columns: [{
            header: message.get('message.list.id'),
            width: 20,
            dataIndex: 'index',
            sortable: false
        }, 
		{
            header: msMessage.get('ui.measurespecification.stature'),
            dataIndex: 'ctStature',
            sortable: true
        }, {
            header: message.get('message.edit.collar'),
            dataIndex: 'ctCollarType',
            sortable: true
        },{
            header: msMessage.get('ui.measurespecification.patronage'),
            dataIndex: 'patronage',
            sortable: true
        },{
            header: message.get('message.edit.customerreference'),
            dataIndex: 'customerReference',
            sortable: true
        },
//		{
//            header: message.get('message.edit.customername'),
//            dataIndex: 'biFranceCustomer',
//            sortable: true
//        },
		{
            header: message.get('message.list.select'),
            width: 20,
            dataIndex: 'id',
            sortable: false,
            renderer: renderSelectItem
        }],
        viewConfig: {
            forceFit: true
        },
        loadMask: true,
        renderTo: 'msDiv',
        bbar: new Ext.PagingToolbar({
            pageSize: 20,
            store: msStore,
            displayInfo: true
        })
    });
    
    var startPage = getPrarmeterValue(window.location, 'startPage');
    var start;
    if (startPage == null || startPage == '') {
        start = 0;
    }
    else {
        start = (startPage - 1) * 20;
    }
    msStore.load({
        params: {
            start: start,
            limit: 20
        }
    });
    
    var detailWin;
    msGrid.on('rowdblclick', function(grid, rowIndex, e){
        if (!detailWin) {
            detailWin = new Ext.Window({
                title: message.get('message.window.detail'),
                layout: 'fit',
                width: 800,
                height: 650,
                closeAction: 'hide',
                plain: true,
                items: [{
                    id: 'detailPanel',
                    region: 'center',
                    bodyStyle: {
                        background: '#ffffff',
                        padding: '7px'
                    },
                    html: message.get('message.window.empty')
                }]
            });
        }
        
        detailWin.show(this);
        var itemTplMarkup = ['<table cellspacing="0" id="the-table" style="width: 100%;"><tbody>',
			 '<tr><td style="background:#eeeeee; width: 15%;">',
			 message.get('message.list.id'),
			 '</td><td>{id}</td>',
			 '<td style="background:#eeeeee;width: 15%;">',
			 msMessage.get('ui.measurespecification.name'),
			 '</td><td>{name}</td></tr>',
			 '<tr><td style="background:#eeeeee;">',
			 msMessage.get('ui.measurespecification.stature'),
			 '</td><td>{ctStature}</td>',
			 '<td style="background:#eeeeee;">',
			 msMessage.get('message.edit.collar'),
			 '</td><td>{ctCollarType}</td></tr>',
			 '<tr><td style="background:#eeeeee;">', 
			 msMessage.get('ui.measurespecification.photo'), 
			 '</td><td><img id="customImg" height="200" src="../../_temp/{realPhoto1Name}"></td><td style="background:#eeeeee;">', 
			 msMessage.get('ui.measurespecification.photo'), 
			 '</td><td><img id="customImg" height="200" src="../../_temp/{realPhoto2Name}"></td></tr>',
			  '</tbody></table><div id="itemList"></div>'];
        var itemTpl = new Ext.Template(itemTplMarkup);
        var detailPanel = Ext.getCmp('detailPanel');
        itemTpl.overwrite(detailPanel.body, msGrid.getStore().getAt(rowIndex).data);
        
        var listStore = new Ext.data.Store({
            url: '../../servlet/BiMeasureSpecificationServlet?action=100&id=' + msGrid.getStore().getAt(rowIndex).data.id,
            
            reader: new Ext.data.XmlReader({
                record: 'item',
                id: 'id',
                totalRecords: 'itemTotal'
            }, [ 
            'index', 'number', 'designations', 'sizeS', 'sizeM', 'sizeL', 'sizeXl', 'sizeXxl', 'sizeXxxl', 'repeatS', 'repeatM', 'repeatL', 'repeatXl', 'repeatXxl', 'tolerance'])
        });
        
        var listGrid = new Ext.grid.GridPanel({
            title: msMessage.get('ui.measurespecification.itemlisttitle'),
            store: listStore,
            stripeRows: true,
            height: 270,
            columns: [{
                header: message.get('message.list.id'),
                dataIndex: 'index'
            }, {
                header: msMessage.get('ui.measurespecification.itemnumber'),
                dataIndex: 'number'
            }, {
                header: msMessage.get('ui.measurespecification.itemdesignations'),
                dataIndex: 'designations'
            }, {
                header: 'S',
                dataIndex: 'sizeS'
            }, {
                header: 'M',
                dataIndex: 'sizeM'
            }, {
                header: 'L',
                dataIndex: 'sizeL'
            }, {
                header: 'XL',
                dataIndex: 'sizeXl'
            }, {
                header: 'XXL',
                dataIndex: 'sizeXxl'
            }, {
                header: 'XXXL',
                dataIndex: 'sizeXxxl'
            }, {
                header: msMessage.get('ui.measurespecification.repeat') + '_S',
                dataIndex: 'repeatS'
            }, {
                header: msMessage.get('ui.measurespecification.repeat') + '_M',
                dataIndex: 'repeatM'
            }, {
                header: msMessage.get('ui.measurespecification.repeat') + '_L',
                dataIndex: 'repeatL'
            }, {
                header: msMessage.get('ui.measurespecification.repeat') + '_XL',
                dataIndex: 'repeatXl'
            }, {
                header: msMessage.get('ui.measurespecification.repeat') + '_XXL',
                dataIndex: 'repeatXxl'
            }, {
                header: msMessage.get('ui.measurespecification.tolerance'),
                dataIndex: 'tolerance',
                renderer: renderTolerance
            }],
            viewConfig: {
                forceFit: true
            },
            loadMask: true,
            renderTo: 'itemList'
        });
        
        function renderTolerance(value, p, record){
            return String.format('(+/-){0}', value);
        }
        
        listStore.load();
        
        
    });
}

